package com.example.project22_editingmediaplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;

import sharevideo.ShareVideo;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.imagehandling.CameraPreview;
import com.example.imagehandling.FacePreview;
import com.example.minimusicdemo.Main_play;
import com.example.project22_editingmediaplayer.action.AudioUltility;
import com.example.project22_editingmediaplayer.objects.SongObject;
import com.example.project22_editingmediaplayer.resource.SongResource;
import com.example.project22_editingmediaplayer.service.DatabaseService;
import com.example.project22_editingmediaplayer.service.MediaService;
import com.example.project22_editingmediaplayer.service.MediaService.LocalMediaBinder;

public class MainActivity extends FragmentActivity {
	private Context myContext;
	private ViewPager _mViewPager;
	private ViewPagerAdapter _adapter;
	public final static String GET_SONG_BY_RATING = "com.example.project22_editingmediaplayer.GET_SONG_BY_RATING";
	public final static String INSERT_SONG = "com.example.project22_editingmediaplayer.INSERT_SONG";
	public final static String UPDATE_SONG = "com.example.project22_editingmediaplayer.UPDATE_SONG";
	public final static String DELETE_SONG = "com.example.project22_editingmediaplayer.DELETE_SONG";
	public final static String REGISTERSERVICE = "com.example.project22_editingmediaplayer.REGISTERSERVICE";
	public final static String GET_INDEX = "com.example.project22_editingmediaplayer.GET_INDEX";
	LayoutParams params;
	LinearLayout firstTab, secondTab, thirdTab, fourthTab, fivethTab, sixthTab;
	View call_screenplay;
	SongObject song;
	public static TextView namesong;
	public static TextView singer;
	public static ImageButton btnNext;
	public static ImageButton btnPrev;
	public static ImageButton btnPlay;

	public MenuItem menu1;
	TimePicker timePicker;
	int hour;
	int minute;
	TextView tvHour;
	TextView tvMinute;
	// used for register alarm manager
	PendingIntent pendingIntent;
	// used to store running alarmmanager instance
	AlarmManager alarmManager;
	// Callback function for Alarmmanager event
	BroadcastReceiver AlarmReceiver;

	public static MediaService mService;
	public static int asyncFlag;
	private int indexTab = 0;

	public int getIndexTab() {
		return indexTab;
	}

	public void setIndexTab(int indexTab) {
		this.indexTab = indexTab;
	}

	boolean mBound;
	// public static boolean flag = true;

	String prefName = "list_recent";
	AudioUltility auListRecent;

	Intent intent;
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				int index = bundle.getInt("index");
				try {
					song = SongResource.listSong.get(index);
					namesong.setText(song.get_name());
					singer.setText(song.get_artist());
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	};
	private BroadcastReceiver databasereceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
		}
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		myContext = getApplicationContext();

		firstTab = (LinearLayout) findViewById(R.id.first_tab);
		secondTab = (LinearLayout) findViewById(R.id.second_tab);
		thirdTab = (LinearLayout) findViewById(R.id.three_tab);
		fourthTab = (LinearLayout) findViewById(R.id.four_tab);
		fivethTab = (LinearLayout) findViewById(R.id.five_tab);
		sixthTab = (LinearLayout) findViewById(R.id.six_tab);

		namesong = (TextView) findViewById(R.id.songName);
		singer = (TextView) findViewById(R.id.author);
		btnPrev = (ImageButton) findViewById(R.id.bottom_action_bar_previous);
		btnNext = (ImageButton) findViewById(R.id.bottom_action_bar_next);
		btnPlay = (ImageButton) findViewById(R.id.bottom_action_bar_play);

		btnPrev.setOnClickListener(onClick);
		btnPlay.setOnClickListener(onClick);
		btnNext.setOnClickListener(onClick);
		call_screenplay = (View) findViewById(R.id.calltoscreenplay);
		call_screenplay.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (MainActivity.mService.getlistsong() != null) {
					Intent i = new Intent(MainActivity.this, Main_play.class);
					startActivity(i);
					// flag = false;
				}
			}
		});
		auListRecent = new AudioUltility(myContext);

		setUpView();
		setTab();
		params = new LayoutParams(80, LayoutParams.WRAP_CONTENT);
		intent = new Intent(this, MediaService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
		RegisterAlarmBroadcast();
	}

	OnClickListener onClick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == btnPlay) {
				if (MainActivity.mService.getlistsong() != null) {

					if (MainActivity.mService.getMediaPlayer() != null) {
						if (MainActivity.mService.getMediaPlayer().isPlaying()) {
							MainActivity.mService.getMediaPlayer().pause();
							MainActivity.mService.showNotification(
									MainActivity.mService.getIndex(),
									SongResource.listSong
											.get(MainActivity.mService
													.getIndex()));
							btnPlay.setImageResource(R.drawable.apollo_holo_light_play);
						} else {
							MainActivity.mService.getMediaPlayer().start();
							btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
							MainActivity.mService.showNotification(
									MainActivity.mService.getIndex(),
									SongResource.listSong
											.get(MainActivity.mService
													.getIndex()));
						}
					} else {
					}
				}
			}
			if (v == btnNext) {
				if (MainActivity.mService.getlistsong() != null) {
					MainActivity.mService.nextSong();
					SongObject songObject = SongResource.listSong
							.get(MainActivity.mService.getIndex());
					namesong.setText(songObject.get_name());
					singer.setText(songObject.get_artist());
					btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
				}
			}
			if (v == btnPrev) {
				if (MainActivity.mService.getlistsong() != null) {
					MainActivity.mService.previusSong();
					SongObject songObject = SongResource.listSong
							.get(MainActivity.mService.getIndex());
					namesong.setText(songObject.get_name());
					singer.setText(songObject.get_artist());
					btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
				}
			}
		}
	};

	private void setUpView() {
		_mViewPager = (ViewPager) findViewById(R.id.viewPager);
		_adapter = new ViewPagerAdapter(getApplicationContext(),
				getSupportFragmentManager());
		_mViewPager.setAdapter(_adapter);
		_mViewPager.setCurrentItem(0);
	}

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			mBound = false;
			mService = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			LocalMediaBinder binder = (LocalMediaBinder) service;
			mService = binder.getMediaService();
			mBound = true;
		}
	};

	private void setTab() {
		_mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int position) {
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				switch (position) {
				case 0:
					setIndexTab(0);
					firstTab.setVisibility(View.VISIBLE);
					secondTab.setVisibility(View.INVISIBLE);
					thirdTab.setVisibility(View.INVISIBLE);
					fourthTab.setVisibility(View.INVISIBLE);
					fivethTab.setVisibility(View.INVISIBLE);
					sixthTab.setVisibility(View.INVISIBLE);

					break;

				case 1:
					setIndexTab(1);
					firstTab.setVisibility(View.INVISIBLE);
					secondTab.setVisibility(View.VISIBLE);
					thirdTab.setVisibility(View.INVISIBLE);
					fourthTab.setVisibility(View.INVISIBLE);
					fivethTab.setVisibility(View.INVISIBLE);
					sixthTab.setVisibility(View.INVISIBLE);

					break;
				case 2:
					setIndexTab(2);
					firstTab.setVisibility(View.INVISIBLE);
					secondTab.setVisibility(View.INVISIBLE);
					thirdTab.setVisibility(View.VISIBLE);
					fourthTab.setVisibility(View.INVISIBLE);
					fivethTab.setVisibility(View.INVISIBLE);
					sixthTab.setVisibility(View.INVISIBLE);

					break;
				case 3:
					setIndexTab(3);
					firstTab.setVisibility(View.INVISIBLE);
					secondTab.setVisibility(View.INVISIBLE);
					thirdTab.setVisibility(View.INVISIBLE);
					fourthTab.setVisibility(View.VISIBLE);
					fivethTab.setVisibility(View.INVISIBLE);
					sixthTab.setVisibility(View.INVISIBLE);

					break;
				case 4:
					setIndexTab(4);
					firstTab.setVisibility(View.INVISIBLE);
					secondTab.setVisibility(View.INVISIBLE);
					thirdTab.setVisibility(View.INVISIBLE);
					fourthTab.setVisibility(View.INVISIBLE);
					fivethTab.setVisibility(View.VISIBLE);
					sixthTab.setVisibility(View.INVISIBLE);
					break;
				case 5:
					setIndexTab(5);
					firstTab.setVisibility(View.INVISIBLE);
					secondTab.setVisibility(View.INVISIBLE);
					thirdTab.setVisibility(View.INVISIBLE);
					fourthTab.setVisibility(View.INVISIBLE);
					fivethTab.setVisibility(View.INVISIBLE);
					sixthTab.setVisibility(View.VISIBLE);
					break;
				}
			}

		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(MediaService.NOTIFICATION));
		registerReceiver(databasereceiver, new IntentFilter(
				MainActivity.REGISTERSERVICE));
		this.restoringPreferences();

	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
		unregisterReceiver(databasereceiver);
	}

	public void savingPreferences() {
		// tạo đối tượng getSharedPreferences
		SharedPreferences pre = getSharedPreferences(prefName, MODE_PRIVATE);
		// tạo đối tượng Editor để lưu thay đổi
		SharedPreferences.Editor editor = pre.edit();

		// lưu vào editor
		if (!SongResource.listSong.isEmpty()) {
			editor.clear();
			editor.putInt("size", SongResource.listSong.size());
			for (int i = 0; i < SongResource.listSong.size(); i++) {
				editor.putInt(String.valueOf(i), SongResource.listSong.get(i)
						.get_id());
				Log.e("saving preference",
						String.valueOf(SongResource.listSong.get(i).get_id()));

			}

		} else {
			editor.clear();
			editor.putInt("size", SongResource.sharePrefList.size());
			for (int i = 0; i < SongResource.sharePrefList.size(); i++) {
				editor.putInt(String.valueOf(i),
						SongResource.sharePrefList.get(i));
				Log.e("saving preference",
						String.valueOf(SongResource.sharePrefList.get(i)));

			}
		}

		// chấp nhận lưu xuống file
		editor.commit();
	}

	/**
	 * hàm đọc trạng thái đã lưu trước đó
	 */
	public ArrayList<Integer> restoringPreferences() {
		SharedPreferences pre = getSharedPreferences(prefName, MODE_PRIVATE);
		int size = pre.getInt("size", 0);
		SongResource.sharePrefList.clear();
		if (size > 0) {
			for (int i = 0; i < size; i++) {
				SongResource.sharePrefList
						.add(pre.getInt(String.valueOf(i), 0));
				Log.e("get preference",
						String.valueOf(pre.getInt(String.valueOf(i), 0)));
			}
			return SongResource.sharePrefList;
		} else
			return null;
	}

	@Override
	public void onBackPressed() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(true);
		builder.setTitle(getString(R.string.dialogtitle));
		builder.setMessage("Do you want to quit SMP");
		builder.setInverseBackgroundForced(true);
		builder.setPositiveButton(getString(R.string.yes),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();

						if (mBound) {
							unbindService(mConnection);
							mBound = false;
						}
						finish();
					}
				});
		builder.setNegativeButton(R.string.no,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		menu1 = menu.findItem(R.id.clock);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		// add vao Sad playlist
		case R.id.item1:
			ArrayList<SongObject> listSongAddToDatabase = new ArrayList<SongObject>();
			listSongAddToDatabase = LayoutAllSong.getSongSelected();

			for (int i = 0; i < listSongAddToDatabase.size(); i++) {
				Log.d("duongw coong taans",
						String.valueOf(listSongAddToDatabase.get(i).get_id()));
				Intent intentoDatabaseService = new Intent();
				intentoDatabaseService.setAction(MainActivity.INSERT_SONG);
				intentoDatabaseService.putExtra("id", listSongAddToDatabase
						.get(i).get_id());
				intentoDatabaseService.putExtra("flag", 3);
				startService(intentoDatabaseService);
			}
			if (listSongAddToDatabase == null) {
				Toast toast = Toast.makeText(MainActivity.this,
						"no song is selected!", Toast.LENGTH_SHORT);
				toast.show();
			} else {
				Toast toast = Toast.makeText(MainActivity.this,
						"saved into sad album!", Toast.LENGTH_SHORT);
				toast.show();
			}
			break;

		// add list bai hat da chon vao Happy
		case R.id.item2:
			ArrayList<SongObject> listSongHappyToDatabase = new ArrayList<SongObject>();
			listSongHappyToDatabase = LayoutAllSong.getSongSelected();
			for (int i = 0; i < listSongHappyToDatabase.size(); i++) {
				Log.d("duongw coong taans",
						String.valueOf(listSongHappyToDatabase.get(i).get_id()));
				Intent intentoDatabaseService = new Intent();
				intentoDatabaseService.setAction(MainActivity.INSERT_SONG);
				intentoDatabaseService.putExtra("id", listSongHappyToDatabase
						.get(i).get_id());
				intentoDatabaseService.putExtra("flag", 1);
				startService(intentoDatabaseService);
			}
			if (listSongHappyToDatabase == null) {
				Toast toast = Toast.makeText(MainActivity.this,
						"no song is selected!", Toast.LENGTH_SHORT);
				toast.show();
			} else {
				Toast toast = Toast.makeText(MainActivity.this,
						"saved into sad album!", Toast.LENGTH_SHORT);
				toast.show();
			}
			break;
		case R.id.item3:

			ArrayList<SongObject> listSongFunnyToDatabase = new ArrayList<SongObject>();
			listSongFunnyToDatabase = LayoutAllSong.getSongSelected();
			for (int i = 0; i < listSongFunnyToDatabase.size(); i++) {
				Log.d("duongw coong taans",
						String.valueOf(listSongFunnyToDatabase.get(i).get_id()));
				Intent intentoDatabaseService = new Intent();
				intentoDatabaseService.setAction(MainActivity.INSERT_SONG);
				intentoDatabaseService.putExtra("id", listSongFunnyToDatabase
						.get(i).get_id());
				intentoDatabaseService.putExtra("flag", 2);
				startService(intentoDatabaseService);
			}
			if (listSongFunnyToDatabase == null) {
				Toast toast = Toast.makeText(MainActivity.this,
						"no song is selected!", Toast.LENGTH_SHORT);
				toast.show();
			} else {
				Toast toast = Toast.makeText(MainActivity.this,
						"saved into sad album!", Toast.LENGTH_SHORT);
				toast.show();
			}
			break;
		case R.id.playall:
			ArrayList<SongObject> listSongPlayAllSong = new ArrayList<SongObject>();
			listSongPlayAllSong = new AudioUltility(myContext).getAllSong();
			if (!listSongPlayAllSong.isEmpty()) {
				SongResource.listSong.clear();
				SongResource.listSong.addAll(listSongPlayAllSong);
				SongObject songObject = SongResource.listSong.get(0);
				namesong.setText(songObject.get_name());
				singer.setText(songObject.get_artist());
				btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
				Intent i = new Intent(MainActivity.this, Main_play.class);
				startActivity(i);
				MainActivity.mService.PlaySong(0);
				btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
			}
			break;
		case R.id.playselected:
			if (getIndexTab() == 0) {
				ArrayList<SongObject> listSongPlaySelected = new ArrayList<SongObject>();
				if (!LayoutAllSong.getSongSelected().isEmpty()) {
					listSongPlaySelected = LayoutAllSong.getSongSelected();
					SongResource.listSong.clear();
					SongResource.listSong.addAll(listSongPlaySelected);
					SongObject songObject = SongResource.listSong.get(0);
					namesong.setText(songObject.get_name());
					singer.setText(songObject.get_artist());
					btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
					Intent i = new Intent(MainActivity.this, Main_play.class);
					startActivity(i);
					MainActivity.mService.PlaySong(0);
					MainActivity.mService.flag_first = false;
					btnPlay.setImageResource(R.drawable.apollo_holo_light_pause);
				} else {
				}
			}
			break;
		case R.id.addfavorite:
			ArrayList<SongObject> listSongFavoriteToDatabase = new ArrayList<SongObject>();
			listSongFavoriteToDatabase = LayoutAllSong.getSongSelected();
			for (int i = 0; i < listSongFavoriteToDatabase.size(); i++) {
				Log.d("duongw coong taans", String
						.valueOf(listSongFavoriteToDatabase.get(i).get_id()));
				Intent intentoDatabaseService = new Intent();
				intentoDatabaseService.setAction(MainActivity.INSERT_SONG);
				intentoDatabaseService.putExtra("id",
						listSongFavoriteToDatabase.get(i).get_id());
				intentoDatabaseService.putExtra("flag", 0);
				startService(intentoDatabaseService);
			}
			if (listSongFavoriteToDatabase == null) {
				Toast toast = Toast.makeText(MainActivity.this,
						"no song is selected!", Toast.LENGTH_SHORT);
				toast.show();
			} else {
				Toast toast = Toast.makeText(MainActivity.this,
						"saved into sad album!", Toast.LENGTH_SHORT);
				toast.show();
			}
			break;

		case R.id.equalizer:
			Intent i = new Intent(MainActivity.this, AudioFxDemo.class);
			startActivity(i);
			break;

		case R.id.videoshare:
			Intent i1 = new Intent(MainActivity.this, ShareVideo.class);
			i1.putExtra("key", "share");
			startActivity(i1);
			break;
		case R.id.nhandang:
//			Intent i2 = new Intent(MainActivity.this, FacePreview.class);
//			startActivity(i2);
			break;
		case R.id.addintonowplay:
			ArrayList<SongObject> addintonowplay = new ArrayList<SongObject>();
			addintonowplay = LayoutAllSong.getSongSelected();
			try {
				SongResource.listSong.addAll(addintonowplay);
			} catch (Exception e) {
				// TODO: handle exception
			}
			break;
		case R.id.deleteSongInStorage:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(true);
			builder.setTitle(getString(R.string.dialogtitle));
			builder.setMessage("Do you want to delete!");
			builder.setInverseBackgroundForced(true);
			builder.setPositiveButton(getString(R.string.yes),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							ArrayList<SongObject> listSongDelete = new ArrayList<SongObject>();
							listSongDelete = LayoutAllSong.getSongSelected();
							deleteSongInStorage(listSongDelete);
						}
					});
			builder.setNegativeButton(R.string.no,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			AlertDialog alert = builder.create();
			alert.show();

			break;
		case R.id.timer:
			LayoutInflater mInflater = getLayoutInflater();
			View view = mInflater.inflate(R.layout.layout_setclock, null);
			timePicker = (TimePicker) view.findViewById(R.id.setclock);
			tvHour = (TextView) view.findViewById(R.id.hour);
			tvMinute = (TextView) view.findViewById(R.id.minute);
			tvHour.setText(String.valueOf(hour));

			tvMinute.setText(String.valueOf(minute));
			AlertDialog.Builder clockBuilder = new AlertDialog.Builder(this);
			clockBuilder.setView(view);
			clockBuilder.setTitle("Set Timer!");
			RegisterAlarmBroadcast();
			clockBuilder.setPositiveButton(getString(R.string.yes),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

							hour = timePicker.getCurrentHour();
							minute = timePicker.getCurrentMinute();
							Calendar cal = Calendar.getInstance();

							int minuteCurrent = cal.get(Calendar.MINUTE);
							Log.e("minuteCurrent",
									String.valueOf(minuteCurrent));
							// 24 hour format
							int hourofdayCurrent = cal
									.get(Calendar.HOUR_OF_DAY);
							Log.e("hourCurrent",
									String.valueOf(hourofdayCurrent));

							int distanceTimeByMinute = (hour - hourofdayCurrent)
									* 60 + minute - minuteCurrent;
							if (distanceTimeByMinute > 0) {
								menu1.setVisible(true);
								Toast toast = Toast.makeText(MainActivity.this,
										String.valueOf(distanceTimeByMinute)
												+ " minute" + " left!",
										Toast.LENGTH_SHORT);
								toast.show();
								alarmManager.set(AlarmManager.RTC_WAKEUP,
										System.currentTimeMillis()
												+ distanceTimeByMinute * 60
												* 1000, pendingIntent);
							} else {
								Toast toast = Toast.makeText(MainActivity.this,
										"You need set timer again!",
										Toast.LENGTH_SHORT);
								toast.show();
							}
						}
					});
			clockBuilder.setNegativeButton(R.string.no,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			AlertDialog alert1 = clockBuilder.create();
			alert1.show();
			break;
		case R.id.clock:

			AlertDialog.Builder clock = new AlertDialog.Builder(this);
			clock.setTitle("timer!");
			clock.setMessage("Do you want turn off timer!");
			clock.setPositiveButton(getString(R.string.yes),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							menu1.setVisible(false);
							UnregisterAlarmBroadcast();
						}
					});
			clock.setNegativeButton(R.string.no,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});

			AlertDialog alert2 = clock.create();
			alert2.show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void deleteSongInStorage(ArrayList<SongObject> ls) {
		AudioUltility au = new AudioUltility(myContext);
		try {
			for (int i = 0; i < ls.size(); i++) {
				File file = new File(au.getOneSongById(ls.get(i).get_id())
						.get_path());
				file.delete();
				Intent intentDelete = new Intent();
				intentDelete.setAction(MainActivity.DELETE_SONG);
				intentDelete.putExtra("idDelete", ls.get(i).get_id());
				startService(intentDelete);
				au.deleteSongInMediaStore(ls.get(i).get_id());
				for (int j = 0; j < SongResource.sharePrefList.size(); j++) {
					if (ls.get(i).get_id() == SongResource.sharePrefList.get(j)) {
						SongResource.sharePrefList.remove(j);
					}
				}
				for (int j = 0; j < SongResource.listSong.size(); j++) {
					if (ls.get(i).get_id() == SongResource.listSong.get(j)
							.get_id()) {
						SongResource.listSong.remove(j);
					}
				}
			}
			Toast toast = Toast.makeText(MainActivity.this, "deleted!",
					Toast.LENGTH_SHORT);
			toast.show();

		} catch (Exception e) {
			// TODO: handle exception
			Toast toast = Toast.makeText(MainActivity.this, "no song deleted!",
					Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		savingPreferences();
		NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationmanager.cancel(0);

		if (mBound) {
			unbindService(mConnection);
			mBound = false;
		}
		stopService(intent);
		Intent abc = new Intent(this, DatabaseService.class);
		stopService(abc);
		unregisterReceiver(AlarmReceiver);
	}

	private void UnregisterAlarmBroadcast() {
		alarmManager.cancel(pendingIntent);
		getBaseContext().unregisterReceiver(AlarmReceiver);
	}

	private void RegisterAlarmBroadcast() {
		// This is the call back function(BroadcastReceiver) which will be call
		// when your
		// alarm time will reached.
		AlarmReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Toast.makeText(context, "Chúc đệ Việt ngủ ngon :))",
						Toast.LENGTH_LONG).show();
				MainActivity.this.finish();

			}
		};

		// register the alarm broadcast here
		registerReceiver(AlarmReceiver, new IntentFilter(
				"com.example.project22-editingmediaplayer"));
		pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(
				"com.example.project22-editingmediaplayer"), 0);
		alarmManager = (AlarmManager) (this
				.getSystemService(Context.ALARM_SERVICE));
	}

}